<?php

namespace App\Models\Vuls;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class Category extends Model
{
    //使用软删除
    use SoftDeletes;
    //关联表
    protected $table = 'category';
    //设置主键
    protected $primaryKey = 'id';
    //软删除自动维护字段,不为空时此条数据不显示
    protected $dates = ['deleted_at'];
    /**
     * childCategory 主外键关联
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function childCategory() {
        return $this->hasMany('App\Models\Vuls\Category', 'pid', 'id')->select('id','name','pid');
    }

    /**
     * allChildrenCategorys 数据关联
     *
     * @return $this
     */
    public function allChildrenCategorys()
    {
        return $this->childCategory()->with('allChildrenCategorys')->select('id','name','pid');
    }

    /**
     * getCateNames 获取分类名称
     *
     * @param bool $id
     * @return \Illuminate\Support\Collection
     */
    public static function getCateNames($id = false){
        $where = $id ? [['pid', '=', $id]] : [['pid', '=', '0']];
        return DB::table('category')
            ->select('id', 'name', 'pid')
            ->where($where)
            ->get();
    }
}
